package top.hmtools.captcha;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import top.hmtools.captcha.cache.SimpleCahceHandle;
import top.hmtools.captcha.configuration.CaptchaAutoConfiguration;

/**
 * 验证码组件上下文
 * 
 * @author Hybomyth
 *
 */
@Component
public class CaptchaContext {
	
	private final Logger logger = LoggerFactory.getLogger(CaptchaContext.class);


	@Autowired
	private CaptchaAutoConfiguration captchaAutoConfiguration;

	/**
	 * 检查客户端传入的 验证码 值 与session 中 验证码值 是否一致
	 * 
	 * @param clientCode
	 * @return
	 */
	public boolean checkCaptcha(String clientCode) {
		// 获取验证码值
		Object sessionCodeObj = this.captchaAutoConfiguration.getSession()
				.getAttribute(CaptchaAutoConfiguration.SESSION_CAPTCHA_KEY);
		
		//再尝试从缓存中获取  验证码
		if(sessionCodeObj == null){
			String uuidParam = this.captchaAutoConfiguration.getRequest().getParameter(this.captchaAutoConfiguration.getUuidParamName());
			if(uuidParam != null && uuidParam.length()>0){
				sessionCodeObj = SimpleCahceHandle.getAttribute(uuidParam, CaptchaAutoConfiguration.SESSION_CAPTCHA_KEY);
			}
		}
		
		if (sessionCodeObj == null) {
			if(this.logger.isDebugEnabled()){
				this.logger.debug("session中的验证码为null");
			}
			return false;
		}
		String sessionCode = String.valueOf(sessionCodeObj);
		if (sessionCode == null || clientCode == null || sessionCode.isEmpty() || clientCode.isEmpty()) {
			if(this.logger.isDebugEnabled()){
				this.logger.debug("session中、请求参数中的验证码为空");
			}
			return false;
		}

		// 获取时间戳
		Object timestampObj = this.captchaAutoConfiguration.getSession()
				.getAttribute(CaptchaAutoConfiguration.SESSION_CAPTCHA_TIMESTAMP_KEY);
		
		//再尝试从缓存中获取  验证码
			if(timestampObj == null){
				String uuidParam = this.captchaAutoConfiguration.getRequest().getParameter(this.captchaAutoConfiguration.getUuidParamName());
				if(uuidParam != null && uuidParam.length()>0){
					timestampObj = SimpleCahceHandle.getAttribute(uuidParam, CaptchaAutoConfiguration.SESSION_CAPTCHA_TIMESTAMP_KEY);
				}
			}
		
		if (timestampObj == null) {
			if(this.logger.isDebugEnabled()){
				this.logger.debug("session中的时间戳为null");
			}
			return false;
		}
		long timestamp = Long.parseLong(timestampObj.toString());
		if (System.currentTimeMillis() - timestamp > this.captchaAutoConfiguration.getTimeout()) {
			if(this.logger.isDebugEnabled()){
				this.logger.debug("session中的验证码已超时");
			}
			return false;
		}
		
		if(this.logger.isDebugEnabled()){
			this.logger.debug("session中的验证码为：{}",sessionCode);
		}
		return sessionCode.equalsIgnoreCase(clientCode);
	}
}
